from PyQt6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, 
                                    QLabel, QLineEdit, QComboBox,
                                    QPushButton, QFormLayout)
from logger import logger
from config import ROOT_DIR
import os
import json
from dotenv import load_dotenv

class SettingsDialog(QDialog):
    def __init__(self, ai_service, parent=None):
        super().__init__(parent)
        self.ai_service = ai_service
        logger.info("初始化AI服务配置对话框")
        self.init_ui()
        
    def _load_config_values(self):
        """从配置文件加载配置项的值"""
        
        # 使用项目根目录的配置文件路径
        self.active_config_path = os.path.join(ROOT_DIR, 'config.json')
        self.active_env_path = os.path.join(ROOT_DIR, '.env')

        logger.info(f"加载配置文件: {self.active_config_path}")
        logger.info(f"加载环境变量文件: {self.active_env_path}")
        
        try:
            # 读取配置文件
            if os.path.exists(self.active_config_path):
                with open(self.active_config_path, 'r', encoding='utf-8') as f:
                    self.config_data = json.load(f)
            else:
                self.config_data = {}
            
            logger.info(f"配置文件内容: {self.config_data}")
            
            # 加载.env文件
            if os.path.exists(self.active_env_path):
                load_dotenv(self.active_env_path)
            
            logger.info(f"环境变量OPENAI_API_KEY: {os.getenv('OPENAI_API_KEY', '')}")
            logger.info(f"环境变量OPENAI_API_BASE: {os.getenv('OPENAI_API_BASE', 'https://api.openai.com/v1')}")
                
            # 加载环境变量
            self.env_values = {
                'api_key': os.getenv('OPENAI_API_KEY', ''),
                'api_base': os.getenv('OPENAI_API_BASE', 'https://api.openai.com/v1')
            }
            
        except Exception as e:
            logger.error(f"加载配置文件失败: {str(e)}")
            self.config_data = {}
            self.env_values = {
                'api_key': '',
                'api_base': 'https://api.openai.com/v1'
            }
            self.active_config_path = os.path.join(ROOT_DIR, 'config.json')
            self.active_env_path = os.path.join(ROOT_DIR, '.env')

    def init_ui(self):
        self.setWindowTitle('AI供应商配置')
        self.setMinimumWidth(400)
        
        # 加载配置文件的值
        self._load_config_values()
        
        layout = QVBoxLayout(self)
        form_layout = QFormLayout()
        
        # 供应商选择
        self.provider_combo = QComboBox()
        self.provider_combo.addItems(['OpenAI', 'Ollama'])
        provider = self.config_data.get('provider', 'openai').capitalize()
        self.provider_combo.setCurrentText(provider)
        form_layout.addRow('供应商:', self.provider_combo)
        
        # API密钥输入
        self.api_key_edit = QLineEdit()
        self.api_key_edit.setText(self.env_values.get('api_key', ''))
        self.api_key_edit.setEchoMode(QLineEdit.EchoMode.Password)
        form_layout.addRow('API密钥:', self.api_key_edit)
        
        # API地址输入
        self.api_base_edit = QLineEdit()
        self.api_base_edit.setText(self.env_values.get('api_base', 'https://api.openai.com/v1'))
        form_layout.addRow('API地址:', self.api_base_edit)
        
        # 模型选择
        self.model_combo = QComboBox()
        self.model_combo.setEditable(True)
        self.model_combo.addItems([
            'gpt-3.5-turbo',
            'gpt-4',
            'deepseek-coder',
            'qwen-max', 
            'glm-4',
            'mixtral-8x7b'
        ])
        model = self.config_data.get('model', 'gpt-3.5-turbo')
        self.model_combo.setCurrentText(model)
        form_layout.addRow('模型:', self.model_combo)
        
        layout.addLayout(form_layout)
        
        # 按钮布局
        button_layout = QHBoxLayout()
        
        save_btn = QPushButton('保存')
        save_btn.clicked.connect(self.save_settings)
        
        cancel_btn = QPushButton('取消')
        cancel_btn.clicked.connect(self.reject)
        
        button_layout.addWidget(save_btn)
        button_layout.addWidget(cancel_btn)
        layout.addLayout(button_layout)
        
    def save_settings(self):
        """保存设置并更新AI服务配置"""
        provider = self.provider_combo.currentText().lower()
        model = self.model_combo.currentText()
        logger.info(f"保存AI服务配置: provider={provider}, model={model}")
        
        # 更新AI服务配置，传入活动配置文件路径
        self.ai_service.update_config(
            provider=self.provider_combo.currentText().lower(),
            api_key=self.api_key_edit.text(),
            api_base=self.api_base_edit.text(),
            model=self.model_combo.currentText(),
            config_path=self.active_config_path,  # 传入实际使用的配置文件路径
            env_path=self.active_env_path  # 传入实际使用的环境变量文件路径
        )
        self.accept()
